/*
 * APITable <https://github.com/apitable/apitable>
 * Copyright (C) 2022 APITable Ltd. <https://apitable.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.apitable.space.controller;

import com.apitable.core.support.ResponseData;
import com.apitable.interfaces.social.facade.SocialServiceFacade;
import com.apitable.organization.mapper.MemberMapper;
import com.apitable.shared.cache.service.UserSpaceCacheService;
import com.apitable.shared.component.notification.NotificationTemplateId;
import com.apitable.shared.component.notification.annotation.Notification;
import com.apitable.shared.component.scanner.annotation.ApiResource;
import com.apitable.shared.component.scanner.annotation.GetResource;
import com.apitable.shared.component.scanner.annotation.PostResource;
import com.apitable.shared.constants.ParamsConstants;
import com.apitable.shared.context.LoginContext;
import com.apitable.shared.context.SessionContext;
import com.apitable.space.enums.SpaceUpdateOperate;
import com.apitable.space.ro.SpaceMainAdminChangeOpRo;
import com.apitable.space.service.ISpaceInviteLinkService;
import com.apitable.space.service.ISpaceService;
import com.apitable.space.vo.MainAdminInfoVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import java.util.Collections;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * Space - Main Admin Api.
 */
@RestController
@Tag(name = "Space - Main Admin Api")
@ApiResource(path = "/space")
public class SpaceMainAdminController {

    @Resource
    private ISpaceService iSpaceService;

    @Resource
    private MemberMapper memberMapper;

    @Resource
    private UserSpaceCacheService userSpaceCacheService;

    @Resource
    private ISpaceInviteLinkService iSpaceInviteLinkService;

    @Resource
    private SocialServiceFacade socialServiceFacade;

    /**
     * Get main admin info.
     */
    @GetResource(path = "/manager")
    @Operation(summary = "Get main admin info")
    @Parameter(name = ParamsConstants.SPACE_ID, description = "space id", required = true,
        schema = @Schema(type = "string"), in = ParameterIn.HEADER, example = "spcyQkKp9XJEl")
    public ResponseData<MainAdminInfoVo> getMainAdminInfo() {
        String spaceId = LoginContext.me().getSpaceId();
        MainAdminInfoVo vo = memberMapper.selectAdminInfoBySpaceId(spaceId);
        return ResponseData.success(vo);
    }

    /**
     * Change main admin.
     */
    @Notification(templateId = NotificationTemplateId.SPACE_ADD_PRIMARY_ADMIN)
    @PostResource(path = "/changeManager", tags = "UPDATE_MAIN_ADMIN")
    @Operation(summary = "Change main admin")
    @Parameter(name = ParamsConstants.SPACE_ID, description = "space id", required = true,
        schema = @Schema(type = "string"), in = ParameterIn.HEADER, example = "spcyQkKp9XJEl")
    public ResponseData<Void> replace(@RequestBody @Valid SpaceMainAdminChangeOpRo opRo) {
        Long userId = SessionContext.getUserId();
        Long memberId = LoginContext.me().getMemberId();
        String spaceId = LoginContext.me().getSpaceId();
        socialServiceFacade.checkWhetherSpaceCanChangeMainAdmin(spaceId, memberId,
            opRo.getMemberId(), Collections.singletonList(SpaceUpdateOperate.UPDATE_MAIN_ADMIN));
        Long id = iSpaceService.changeMainAdmin(spaceId, opRo.getMemberId());
        // When the function of inviting all members of the space is turned off,
        // all public invitation links generated by the original main administrator become invalid.
        iSpaceInviteLinkService.delByMemberIdIfNotInvite(spaceId, memberId);
        // delete the relevant cache
        userSpaceCacheService.delete(userId, spaceId);
        userSpaceCacheService.delete(id, spaceId);
        return ResponseData.success();
    }
}
